<template>
  <div class="legend-index">
    <p class="index-title">
      {{ airName }} ({{ airUnit }})
      <span @click="setAutoValue">自动设置</span>
    </p>
    <p class="index-range">
      <n-input
        v-model:value="minValue"
        style="width: 150px"
        type="text"
        :allow-input="onlyAllowNumber"
        placeholder="最小值"
      />
      ~
      <n-input
        v-model:value="maxValue"
        style="width: 150px"
        :allow-input="onlyAllowNumber"
        type="text"
        placeholder="最大值"
      />
    </p>
    <p class="index-btns">
      <span style="background: #374367;" @click="cancelIndex">取消</span>
      <span style="background: #3F7FDC;" @click="saveIndex">保存</span>
    </p>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, watch } from 'vue'
export default {
  props: {
    featureList: {
      type: Array,
      default: () => []
    },
    airName: {
      type: String,
      default: ''
    },
    airUnit: {
      type: String,
      default: ''
    }
  },
  emits: ['save', 'close'],
  setup(props, { emit }) {
    const data = reactive({
      minValue: null,
      maxValue: null,
      autoMin: null,
      autoMax: null,
      airName: null,
      airUnit: null
    })

    const getImageUrl = (src) => {
      return new URL(`../../../assets/gis/${src}.png`, import.meta.url).href
    }

    const onlyAllowNumber = (value) => {
      return !value || /^\d+(\.\d{0,2})?$/.test(value)
    }

    const cancelIndex = () => {
      emit('close')
    }

    const saveIndex = () => {
      if (!data.minValue && !data.maxValue) {
        $message.error('请先输入最小值和最大值')
      } else {
        const newMinValue = data.minValue % 1 === 0 ? parseInt(data.minValue) : Number(data.minValue)
        const newMaxValue = data.maxValue % 1 === 0 ? parseInt(data.maxValue) : Number(data.maxValue)
        let bitNum = 0
        if (getDecimalCount(newMinValue) === getDecimalCount(newMaxValue)) { // 位数相等
          if (newMinValue % 1 === 0 && newMaxValue % 1 === 0) {
            bitNum = -2
          } else {
            bitNum = getDecimalCount(newMaxValue) || getDecimalCount(newMinValue)
          }
        } else {
          bitNum = getLargerNumber(getDecimalCount(newMinValue), getDecimalCount(newMaxValue)) // 获取较大的位数
        }
        const difference = (newMaxValue - newMinValue) / 6
        const bit = bitNum + 2
        let range
        if ((newMaxValue - newMinValue) > 6) {
          range = [
            Number(newMinValue.toFixed(bit)),
            Number((newMinValue + difference).toFixed(bit)),
            Number((newMinValue + 2 * difference).toFixed(bit)),
            Number((newMinValue + 3 * difference).toFixed(bit)),
            Number((newMinValue + 4 * difference).toFixed(bit)),
            Number((newMinValue + 5 * difference).toFixed(bit)),
            Number(newMaxValue.toFixed(bit))
          ]
        } else {
          range = avgChunk(newMinValue, newMaxValue, 7)
          range.splice(0, 1, newMinValue)
          range.splice(range.length - 1, 1, newMaxValue)
        }
        emit('save', range)
      }
    }
    // 判断有几位小数
    function getDecimalCount(num) {
      const str = num.toString()
      const decimalIndex = str.indexOf('.')
      if (decimalIndex === -1) {
        return 0
      }
      let count = 0
      for (let i = decimalIndex + 1; i < str.length; i++) {
        if (str[str.length - 1] !== '0') {
          count++
        }
      }
      return count
    }
    function getLargerNumber(num1, num2) {
      if (num1 > num2) return num1
      return num2
    }
    function avgChunk(start, end, numParts) {
      let bitNum = -1
      if (getDecimalCount(start) === getDecimalCount(end)) { // 位数相等
        if (start % 1 === 0 && end % 1 === 0) {
          bitNum = 0
        } else {
          bitNum = getDecimalCount(end) || getDecimalCount(start)
        }
      } else {
        bitNum = getLargerNumber(getDecimalCount(start), getDecimalCount(end)) // 获取较大的位数 // 获取较大的位数
      }
      const chunkSize = Number((end - start) / numParts)
      const result = []
      for (let i = 1; i <= 7; i++) {
        start += chunkSize
        result.push(Number(start.toFixed(bitNum + 2)))
      }
      return result
    }

    const getMinAndMax = (featureArr) => {
      let gridConcentrationMax = 0
      let gridConcentrationMix = featureArr[0].get('valueArr')[0]
      featureArr.forEach(feature => {
        const valueArr = feature.get('valueArr')
        valueArr.map(it => {
          if (gridConcentrationMax < it) {
            gridConcentrationMax = it
          }

          if (gridConcentrationMix > it) {
            gridConcentrationMix = it
          }
        })
      })
      data.autoMax = gridConcentrationMax.toFixed(2)
      data.autoMin = gridConcentrationMix.toFixed(2)
    }

    const setAutoValue = () => {
      data.maxValue = data.autoMax
      data.minValue = data.autoMin
    }

    // watch(() => props.featureList, newVal => {
    //   if (newVal) {
    //     if (newVal?.length > 0) {
    //     //   getMinAndMax(newVal)
    //     }
    //   }
    // })
    watch(() => props.airName, newVal => {
      if (newVal) {
        data.airName = newVal
      }
    })
    watch(() => props.airUnit, newVal => {
      if (newVal) {
        data.airUnit = newVal
      }
    })

    onMounted(() => {
      if (props.featureList) {
        if (props.featureList?.length > 0) {
          getMinAndMax(props.featureList)
        }
      }
      if (props.airName) {
        data.airName = props.airName
      }
      if (props.airUnit) {
        data.airUnit = props.airUnit
      }
    })

    return {
      ...toRefs(data),
      getImageUrl,
      onlyAllowNumber,
      saveIndex,
      cancelIndex,
      setAutoValue
    }
  }

}
</script>

<style lang="scss" scoped>
.legend-index {
    width: 400px;
    background: url('../../../assets/gis/legend-index.png') no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -200px;
    margin-top: -80px;

    p {
        margin: 20px 0;
    }

    .index-title {
        width: 100%;
        height: 35px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-left: 32px;

        span {
            width: 108px;
            height: 35px;
            background: rgba(63, 127, 220, 0.6);
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: rgba(255, 255, 255, 0.8);
            line-height: 35px;
            text-align: center;
        }
    }

    .index-range {
        display: flex;
        justify-content: space-evenly;
    }

    .index-btns {
        height: 26px;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        span {
            width: 89px;
            height: 26px;
            border-radius: 4px;
            text-align: center;
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #FFFFFF;
            line-height: 26px;
        }
    }
}
</style>
